import { defineStore } from 'pinia'
import { getNoopActions, injectState, useRemote, useWorker, wrapSafeActions } from '@/controller/base/index'
import type { Worker } from '@/controller/base/types/worker'
import type { Remote } from '@/controller/base/types/remote'
import type { WasherDryerController } from '../WasherDryer/definition'
import { WasherDryerActions, WasherDryerGetters, createWasherDryerState } from '../WasherDryer/index'
import { DemoBaseActions, createDemoBaseState, setDemoBaseState } from './BaseAppliance'
import { merge } from 'lodash'
import { getDemoProgramActions, getDemoProgramGetters } from './common/Program'
import { WASHER_STAINS } from '@/constants/Command'
import type { DemoDatasource } from '@/demo/types'
import { useProgramEffects } from '../common/Program/program'
import type { ProgramController } from '../common/Program/definition'

let demoDatasource!: DemoDatasource

export function useDemoWasherDryerControl(): WasherDryerController.Control {
  const createDemoWasherDryerState: () => WasherDryerController.State = () =>
    injectState(
      () => merge(createWasherDryerState(), createDemoBaseState()),
      (state) => {
        setDemoBaseState(state, demoDatasource)

        const detailOptions = state._datasource.detail?.option
        if (detailOptions) {
          const stainOptions = detailOptions.find(({ key }) => key === WASHER_STAINS)
          state.stainValue = (stainOptions?.value as string) || ''
        }
      }
    )
  const DemoWasherDryerGetters: WasherDryerController.Getters = {
    ...(getDemoProgramGetters(WasherDryerGetters as ProgramController.Getters) as WasherDryerController.Getters),
    // Demo模式 不使用程序分组功能
    programGroupsConfig: () => null,
    // Demo模式 SMM类型
    isSMM: () => true,
  }
  const DemoWasherDryerActions: WasherDryerController.Actions = wrapSafeActions<
    WasherDryerController.Store,
    WasherDryerController.Actions
  >({
    ...merge(getNoopActions(WasherDryerActions), DemoBaseActions),
    ...getDemoProgramActions(demoDatasource),
  })
  const useDemoStore = defineStore<
    'DemoWasherDryer',
    WasherDryerController.State,
    WasherDryerController.Getters,
    WasherDryerController.Actions
  >('DemoWasherDryer', {
    state: createDemoWasherDryerState,
    getters: DemoWasherDryerGetters,
    actions: DemoWasherDryerActions,
  })

  const store = useDemoStore() as WasherDryerController.Store
  const worker = useWorker(store) as Worker.ApplianceWorker<WasherDryerController.Store>
  const remote = useRemote(store) as Remote.ApplianceRemote<WasherDryerController.Store>
  return { store, worker, remote }
}

export function createDemoWasherDryerControl(datasource: DemoDatasource): WasherDryerController.Control {
  demoDatasource = datasource
  const control = useDemoWasherDryerControl()
  useProgramEffects(control)
  return control
}
